# !/usr/bin/env python
# -*- coding: utf-8 -*-
from model import Table, Schema
from jinja2 import Environment
from util.code import write_file


def create_sql(table: Table):
    sql_list = ["drop table if exists {};".format(table.name)]
    s = """create table {} (\n{}\n) ENGINE=InnoDB {} DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC COMMENT='{}';"""
    cols = []
    auto_str = ""
    primary_key = ""
    for c in table.columns:
        _type = c.type
        if c.size is not None and c.size != '':
            _type += '(' + str(c.size) + ')'
        col = "  `{}` {}".format(c.name, _type)
        if c.auto_increment:
            col += ' auto_increment'
        if c.require:
            col += ' not null'
        if c.type != 'datetime' and c.default != '':
            col += ' default ' + str(c.default)
        if c.type == 'datetime' and c.default != '':
            col += ' default now()'
        if c.comment is not None and c.comment != '':
            col += " comment '" + str(c.comment) + "'"
        cols.append(col)
        if c.auto_increment:
            auto_str = "AUTO_INCREMENT=1"
        if primary_key == "" and c.index == "primary":
            primary_key = c.name
    if primary_key != "":
        cols.append("PRIMARY KEY (`{}`) USING BTREE".format(primary_key))
    col_str = ",\n".join(cols)
    sql_list.append(s.format(table.name, col_str, auto_str, table.comment))
    return "\n".join(sql_list)


def init_schema(schema: Schema, env: Environment):
    tables = schema.tables
    sql_list = []
    for table in tables:
        if not table.enable:
            continue
        sql_list.append(create_sql(table))
    if schema.database is not None and schema.database != "" and len(sql_list) > 0:
        write_file("out/{}.sql".format(schema.database), "\n\n".join(sql_list))
